package pers.liuchengyin.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.queryparser.xml.builders.BooleanQueryBuilder;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import pers.liuchengyin.config.EsConfig;
import pers.liuchengyin.constants.EsConstants;
import pers.liuchengyin.pojo.Result;
import pers.liuchengyin.pojo.SearchParam;
import pers.liuchengyin.pojo.SearchResult;
import pers.liuchengyin.pojo.SkuModel;
import pers.liuchengyin.service.EsSearchService;
import pers.liuchengyin.utils.ResultUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName EsSearchServiceImpl
 * @Description
 * @Author 柳成荫
 * @Date 2022/3/27
 */
@Service
public class EsSearchServiceImpl implements EsSearchService {

    @Qualifier("elasticSearchRestClient")
    @Autowired
    private RestHighLevelClient esClient;


    @Override
    public Result<SearchResult> searchSku(SearchParam param) {
        SearchResult searchResult = null;
        try {
            // 构建检索条件
            SearchRequest searchRequest = buildSearchRequestNew(param);
            SearchResponse response = esClient.search(searchRequest, EsConfig.COMMON_OPTIONS);
            searchResult = buildSearchResult(response,param);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtils.successResult(searchResult);
    }

    private SearchRequest buildSearchRequestNew(SearchParam param) {
        // 构建DSL语句
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // 构建组合查询
        BoolQueryBuilder booleanQuery = QueryBuilders.boolQuery();

        // 1、标题匹配查询
        if (StringUtils.isNotBlank(param.getKeyword())) {
            booleanQuery.must(QueryBuilders.matchQuery("name", param.getKeyword()));
        }
        // 2、过滤分类
        if (Objects.nonNull(param.getCategoryId())) {
            booleanQuery.filter(QueryBuilders.termQuery("categoryId", param.getCategoryId()));
        }
        // 3、过滤品牌
        if (Objects.nonNull(param.getBrandId())) {
            booleanQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 4、过滤属性
        if (!CollectionUtils.isEmpty(param.getSpecs())) {
            param.getSpecs().forEach(spec -> {
                String[] specArr = spec.split("_");
                String specId = specArr[0];
                String[] specValues = specArr[1].split(":");
                BoolQueryBuilder booNestedQuery = QueryBuilders.boolQuery();
                booNestedQuery.must(QueryBuilders.termQuery("specs.id", specId));
                booNestedQuery.must(QueryBuilders.termsQuery("specs.specValue", specValues));
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("specs", booNestedQuery, ScoreMode.None);
                booleanQuery.filter(nestedQuery);
            });
        }
        // 5、过滤库存
        if (Objects.nonNull(param.getHasStock())) {
            booleanQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock()));
        }
        // 6、过滤价格区间
        if (StringUtils.isNotBlank(param.getPrice())) {
            String[] priceArr = param.getPrice().trim().split("_");
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("price");
            if (priceArr.length == 1) {
                if (param.getPrice().startsWith("_")) {
                    rangeQuery.lte(priceArr[0]);
                }else {
                    rangeQuery.gte(priceArr[0]);
                }
            }else if (priceArr.length == 2) {
                if (StringUtils.isNotBlank(priceArr[1])) {
                    rangeQuery.lte(priceArr[1]);
                }
                if (StringUtils.isNotBlank(priceArr[0])) {
                    rangeQuery.gte(priceArr[0]);
                }
            }
            booleanQuery.filter(rangeQuery);
        }
        sourceBuilder.query(booleanQuery);

        // 分页
        sourceBuilder.from(param.getPageNum() - 1);
        sourceBuilder.from((param.getPageNum() - 1) * param.getPageSize());

        // 高亮
        if (StringUtils.isNotBlank(param.getKeyword())) {
            HighlightBuilder highlight = new HighlightBuilder();
            highlight.preTags("</font color = 'red'>");
            highlight.postTags("</b>");
            highlight.field("name");
            sourceBuilder.highlighter(highlight);
        }

        // 聚合
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brandAgg");
        brandAgg.field("brandId").size(10);
        brandAgg.subAggregation(AggregationBuilders.terms("brandNameAgg").field("brandName").size(1));
        sourceBuilder.aggregation(brandAgg);
        // 分类聚合
        TermsAggregationBuilder categoryAgg = AggregationBuilders.terms("categoryAgg");
        categoryAgg.field("categoryId").size(10);
        categoryAgg.subAggregation(AggregationBuilders.terms("categoryNameAgg").field("categoryName").size(1));
        sourceBuilder.aggregation(categoryAgg);
        // 属性聚合
        NestedAggregationBuilder specAgg = AggregationBuilders.nested("specAgg", "specs");
        TermsAggregationBuilder specIdAgg = AggregationBuilders.terms("specIdAgg").field("specs.id");

        TermsAggregationBuilder specNameAgg = AggregationBuilders.terms("specNameAgg").field("specs.specName");
        specIdAgg.subAggregation(specNameAgg);

        // 聚合分析出当前id对应的所有可能的属性值
        TermsAggregationBuilder specValueAgg = AggregationBuilders.terms("specValueAgg").field("specs.specValue").size(50);
        specIdAgg.subAggregation(specValueAgg);

        specAgg.subAggregation(specIdAgg);
        sourceBuilder.aggregation(specAgg);

        System.out.println("构建的DSL语句：");
        System.out.println(sourceBuilder.toString());
        return new SearchRequest(new String[]{EsConstants.SKU_INDEX}, sourceBuilder);
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        SearchHits searchHits = response.getInternalResponse().hits();
        if (Objects.nonNull(searchHits) && searchHits.getHits().length > 0) {
            List<SkuModel> skuModelList = new ArrayList<>();
            for (SearchHit hit : searchHits.getHits()) {
                SkuModel skuModel = JSON.parseObject(hit.getSourceAsString(), new TypeReference<SkuModel>(){});
                // 高亮替换
                if (StringUtils.isNotBlank(param.getKeyword())) {
                    HighlightField highlightName = hit.getHighlightFields().get("name");
                    skuModel.setName(highlightName.getFragments()[0].string());
                }
                skuModelList.add(skuModel);
            }
            result.setSkuModels(skuModelList);
        }
        // 属性聚合
        Aggregations aggregations = response.getAggregations();
        ParsedNested specAgg = aggregations.get("specAgg");
        ParsedLongTerms specIdAgg = specAgg.getAggregations().get("specIdAgg");
        List<SearchResult.Spec> specList = new ArrayList<>();
        specIdAgg.getBuckets().forEach(bucket -> {
            SearchResult.Spec spec = new SearchResult.Spec();
            // 获取ID
            Long specId = bucket.getKeyAsNumber().longValue();
            spec.setSpecId(specId);
            // 获取属性名
            String specName = ((ParsedStringTerms) bucket.getAggregations().get("specNameAgg")).getBuckets().get(0).getKeyAsString();
            spec.setSpecName(specName);
            // 获取所有的属性值
            List<String> specValueList = ((ParsedStringTerms) bucket.getAggregations().get("specValueAgg")).getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(Collectors.toList());
            spec.setSpecValue(specValueList);
            specList.add(spec);
        });
        result.setSpecs(specList);

        // 分类聚合
        ParsedLongTerms categoryAgg = aggregations.get("categoryAgg");
        List<SearchResult.Category> categoryList = new ArrayList<>();
        categoryAgg.getBuckets().forEach(bucket -> {
            SearchResult.Category category = new SearchResult.Category();
            category.setCategoryId(bucket.getKeyAsNumber().longValue());
            category.setCatalogName(((ParsedStringTerms) bucket.getAggregations().get("categoryNameAgg")).getBuckets().get(0).getKeyAsString());
            categoryList.add(category);
        });
        result.setCategories(categoryList);

        // 品牌聚合
        ParsedLongTerms brandAgg = aggregations.get("brandAgg");
        List<SearchResult.Brand> brandList = new ArrayList<>();
        brandAgg.getBuckets().forEach(bucket -> {
            SearchResult.Brand brand = new SearchResult.Brand();
            brand.setBrandId(bucket.getKeyAsNumber().longValue());
            brand.setBrandName(((ParsedStringTerms) bucket.getAggregations().get("brandNameAgg")).getBuckets().get(0).getKeyAsString());
            brandList.add(brand);
        });
        result.setBrands(brandList);

        // 分页处理
        result.setPageNum(param.getPageNum());
        Long totalNum = searchHits.getTotalHits().value;
        result.setTotalCount(totalNum);
        result.setTotalPage(totalNum % param.getPageSize() == 0 ? (totalNum / param.getPageSize()) : (totalNum /  param.getPageSize() + 1));

        return result;
    }


}
